package m.store.service;

import m.base.model.StoreInfo;
import m.base.model.UserInfo;
import m.common.model.util.ModelQueryList;
import m.common.model.util.ModelUpdateUtil;
import m.common.model.util.QueryCondition;
import m.common.service.Service;
import m.store.model.MonthRecord;
import m.system.cache.CacheUtil;
import m.system.exception.MException;
import m.system.util.DateUtil;
import m.system.util.GenerateID;

import java.sql.SQLException;
import java.util.Date;
import java.util.List;

public class MonthRecordService extends Service {
    public MonthRecord get(String userOid, Date date, String type) throws SQLException, MException {
        String yearMonth= DateUtil.format(date,MonthRecord.YearMonth_Format);
        MonthRecord model= ModelQueryList.getModel(MonthRecord.class,new String[]{"*"},
            QueryCondition.and(
                QueryCondition.eq("user.oid",userOid),
                QueryCondition.eq("yearMonth",yearMonth),
                QueryCondition.eq("type",type)
            )
        );
        if(null==model){
            model=new MonthRecord();
            model.setOid(GenerateID.generatePrimaryKey());
            model.setUser(CacheUtil.get(UserInfo.class,userOid));
            model.setStore(new StoreInfo());
            model.getStore().setOid(model.getUser().getOrgGroup().getOid());
            model.setYearMonth(yearMonth);
            model.setType(type);
            model.setAmount(0d);
            model.setNum(0);
            ModelUpdateUtil.insertModel(model);
        }
        return model;
    }
    public List<MonthRecord> getList(String userOid,Date date) throws SQLException, MException {
        return ModelQueryList.getModelList(MonthRecord.class,new String[]{"*"},null,
            QueryCondition.and(
                QueryCondition.eq("user.oid",userOid),
                QueryCondition.eq("yearMonth",DateUtil.format(date,MonthRecord.YearMonth_Format))
            )
        );
    }
}
